# -*- coding: utf-8 -*-

import os
import sys

if __name__ == "__main__":
    currentdir = os.path.dirname( os.path.abspath( sys.argv[0] ) )
    basedir = os.path.abspath( os.path.join( currentdir, ".." ) )
    pythondir = basedir
    sys.path.insert( 0, pythondir )
    pass

from logger import get_file_logger
from datetime import timedelta
from picklerpc.msghandler import RequestHandler
from picklerpc.sendmsg import sendmsg
from picklerpc import Server
from time import sleep, time
from service import default_request_timeout, default_niceness_level


__all__ = ['Sqlite3DatabaseHandler', 'Sqlite3DatabaseServer', 'Sqlite3DatabaseManager', 'Sqlite3DatabaseRequest']

#---------------------------------------------

class Sqlite3DatabaseHandler(RequestHandler):
    """
    Do some tasks, maybe in subprocess
    """
    
    def _request_handle(self, data):
        """
        @param data: simple object data
        @type: dict
        
        @return: python simple object data, jsonable via json.dumps
        @rtype: mixed
        """
        result = False
        
        if not (type(data) is dict):
            return result

        if data["task"] == "ping":
            return self.server.ping()
        if data["task"] == "quit":
            return self.server.quit()
        if data["task"] == "query":
            data = data["data"]
            return self.server.query(
                data["name"],
                data["data"],
                data["wait"]
            )
        if data["task"] == "has-result":
            data = data["data"]
            return self.server.has_result(
                data["request-id"]
            )
        if data["task"] == "get-result":
            data = data["data"]
            return self.server.get_result(
                data["request-id"]
            )
        if data["task"] == "get-result-row":
            data = data["data"]
            return self.server.get_result_row(
                data["request-id"]
            )
        return result
    
    pass

#---------------------------------------------

class Sqlite3DatabaseServer(Server):

    stop_event = None

    _query_results = None
    _query_results_lock = None

    _request_id = 0
    _request_id_lock = None

    log = None

    def get_next_request_id(self):
        self._request_id_lock.acquire()
        self._request_id += 1
        req_id = str(self._request_id)
        self._request_id_lock.release()
        return req_id


    def server_activate(self):

        from project.sqlite3_managed import Project
        from service.sqlite3_table import Sqlite3TableManager
        from threading import Lock

        self.log = get_file_logger("Sqlite3DatabaseServer")

        self.m = Sqlite3TableManager()
        self.p = Project(self.m)

        self._query_results = {}
        self._query_results_lock = Lock()

        self._request_id = 0
        self._request_id_lock = Lock()

        return Server.server_activate(self)

    def ping(self):
        return "pong"

    def query(self, name, data, wait=True):

        request_id = self.get_next_request_id()

        self._query_results_lock.acquire()
        self._query_results[ request_id ] = {
            "result" : None,
            "table" : None,
            "req" : None,
            "done" : False
        }

        try:
            table, req = getattr(self.p, name)(*data)
        except Exception:
            table = None
            req = None

        if table is None:
            self._query_results[ request_id ]["done"] = True
            self._query_results[ request_id ]["result"] = req
        else:
            self._query_results[ request_id ]["table"] = table
            self._query_results[ request_id ]["req"] = req

        if not wait:
            del self._query_results[ request_id ]

        self._query_results_lock.release()

        return request_id

    def has_result(self, request_id):
        self._query_results_lock.acquire()
        has = False
        if request_id in self._query_results:
            has = self._query_results[ request_id ]["done"]
            if not has:
                table = self._query_results[ request_id ]["table"]
                req = self._query_results[ request_id ]["req"]
                has = self.p.getTable(table).has_result(table, req)
                if has:
                    self._query_results[ request_id ]["done"] = True
        self._query_results_lock.release()
        return has

    def get_result(self, request_id):
        self._query_results_lock.acquire()
        table = self._query_results[ request_id ]["table"]
        req = self._query_results[ request_id ]["req"]
        if table is None:
            result = req
        else:
            result = self.p.getTable(table).get_result(table, req)
        del self._query_results[ request_id ]
        self._query_results_lock.release()
        return result

    def get_result_row(self, request_id):
        self._query_results_lock.acquire()

        table = self._query_results[ request_id ]["table"]
        req = self._query_results[ request_id ]["req"]

        if table is None:
            result = req
            if type(result) in (list, tuple,):
                if len(result) > 1:
                    data = result[1:]
                    result = result[0]
                    self._query_results[ request_id ]["req"] = data
                elif len(result) <= 1:
                    del self._query_results[ request_id ]
                    if len(result):
                        result = result[0]
                    else:
                        result = None
            else:
                if request_id in self._query_results:
                    del self._query_results[ request_id ]

        else:
            result = self.p.getTable(table).get_result_row(table, req)

        if result is None:
            if request_id in self._query_results:
                del self._query_results[ request_id ]

        self._query_results_lock.release()
        return result

    def quit(self):
        self.log.info("quit event")

        import signal

        self.log.debug("send SIGINT to self")
        os.kill( os.getpid(), signal.SIGINT )

        return True


    def terminate_self(self, signum, frame):
        self.log.debug("got SHUTDOWN signal")
        t_begin = time()

        self.p.close()

        self.m.quit_all()
        while self.m.ping_all():
            sleep(0.1)

        self.server_close()
        t_end = time()
        self.log.info("SHUTDOWN in %s sec" % (timedelta(seconds=t_end - t_begin),))
        return

    pass

#---------------------------------------------


class Sqlite3DatabaseRequest(object):

    manager = None

    def __init__(self, manager):
        self.manager = manager
        pass

    def ping(self):
        return self.manager.sendmsg("ping", {}, 0.1)

    def query(self, name, data, wait=True):
        return self.manager.sendmsg("query", {
            "name" : name,
            "data" : data,
            "wait" : wait
        })

    def has_result(self, result_id):
        return self.manager.sendmsg("has-result", {
            "request-id" : result_id
        }, 0.1)

    def get_result(self, result_id):
        return self.manager.sendmsg("get-result", {
            "request-id" : result_id
        })

    def get_result_row(self, result_id):
        return self.manager.sendmsg("get-result-row", {
            "request-id" : result_id
        })

    def quit(self):
        return self.manager.sendmsg("quit", {}, 0.1)

    pass


#---------------------------------------------

class Sqlite3DatabaseManager(object):

    host = "127.0.1.8"
    port_min = 10000
    port_max = 20000
    port = None
    request = None

    address = None

    log = None

    def __init__(self):
        self.log = get_file_logger("Sqlite3DatabaseManager")
        pass

    def start_service(self):

        import random

        self.port = random.randint(self.port_min, self.port_max)

        self.address = (self.host, self.port,)

        from archive import which
        from subprocess import Popen

        Popen([which("python3"), "service/sqlite3_database.py",
               "--host", "%s" % self.host,
               "--port", "%s" % self.port,
        ])

        # WAIT WHILE SERVICE STARTS

        pings = 100
        runing = False
        t_begin = time()
        while not runing:

            pong = self.get_request().ping()

            if pong == "pong":
                runing = True

            pings -= 1
            if pings <= 0:
                break

        if pings <= 0:
            self.log.error("FAIL TO START service on %r in %s sec" % (
                self.address, timedelta(seconds=time() - t_begin),))
        else:
            self.log.info("STARTED service on %r in %s sec" % (
                self.address, timedelta(seconds=time() - t_begin),))

        return runing

    def sendmsg(self, task, data, timeout=default_request_timeout):
        try:
            result = sendmsg( self.address, {"task":task, "data":data}, timeout=timeout )
        except Exception as e:
            result = None
            self.log.error("SOCKET: %s" % ( e,))
            self.log.debug("FAIL SEND MESSAGE: task=%s, data=%r" % ( task, data,))
        return result

    def quit(self):
        return self.get_request().quit()

    def get_request(self):
        if not self.request:
            self.request = Sqlite3DatabaseRequest(self)
        return self.request

    pass


#---------------------------------------------


def run_service(host, port):

    if hasattr(os, "nice"):
        os.nice(default_niceness_level)

    server = None
    e_code = 0
    try:
        SERVER_ADDRESS = (host, int(port),)

        server = Sqlite3DatabaseServer(SERVER_ADDRESS, Sqlite3DatabaseHandler, bind_and_activate=False)

        import signal

        signal.signal(signal.SIGINT, server.terminate_self)

        server.server_bind()
        server.server_activate()
        server.serve_forever()
    except Exception as e:
        e_code = 1
        if server and server.log:
            server.log.error("run_service: ERROR=%r" % (e,))
        pass

    return e_code

#---------------------------------------------


def launch():

    from argparse import ArgumentParser

    parser = ArgumentParser(description='Run sqlite3 database service.')
    parser.add_argument('--host', dest='host', action='store', type=str,
        help='Listen on TCP address')
    parser.add_argument('--port', dest='port', action='store', type=int,
        help='Listen on TCP port')

    args = parser.parse_args()
    return run_service(args.host, args.port)

if __name__ == "__main__":
    sys.exit(launch())
